package com.kanshu.ksgb.fastread.doudou.module.message.fragment;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.dl7.recycler.helper.RecyclerViewHelper;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseFragment;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.MessageBean;
import com.kanshu.ksgb.fastread.doudou.common.business.event.BindEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.ICancelRefreshing;
import com.kanshu.ksgb.fastread.doudou.common.business.interfaces.IDisposeMessage;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.module.message.adapter.MessageAdapter;
import com.kanshu.ksgb.fastread.doudou.module.message.manager.MessageCenter;
import com.kanshu.ksgb.fastread.doudou.module.message.presenter.MessagePresenter;
import com.kanshu.ksgb.fastread.doudou.module.message.presenter.MessageView;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import me.drakeet.support.toast.ToastCompat;

/**
 * Created by wcy on 2017\6\13 0013.
 */

public class MessageFragment extends BaseFragment implements ICancelRefreshing, MessageView, IDisposeMessage {

    protected RecyclerView mRecylerView;
    EmptyLayout mEmptyLayout;
    TwinklingRefreshLayout mSwipeRefresh;
    MessagePresenter mPresenter;
    List<MessageBean> mMessageBeen = new ArrayList<>();
    MessageAdapter mMessageAdapter;
    Toast mToast;
    String mUserId;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_msg_layout, container, false);
        mRecylerView = view.findViewById(R.id.recyler_view);
        mEmptyLayout = view.findViewById(R.id.empty_layout);
        mSwipeRefresh = view.findViewById(R.id.swipe_refresh);
        init();
        return view;
    }

    private void init() {
        mPresenter = new MessagePresenter(lifeCyclerSubject);
        mPresenter.attachView(this);
        mMessageAdapter = new MessageAdapter(getActivity(), mMessageBeen);
        mRecylerView.setPadding(0, 0, 0, DisplayUtils.dip2px(getActivity(), 10));
        mSwipeRefresh.setBackgroundColor(getResources().getColor(R.color.color_msg_bg));
        SwipeRefreshHelper.init(mSwipeRefresh, () -> mPresenter.controlPage());
        mToast = ToastCompat.makeText(getActivity(), "没有更多数据了", Toast.LENGTH_SHORT);
        RecyclerViewHelper.initRecyclerViewV(getActivity(), mRecylerView, false, mMessageAdapter);
        mPresenter.loadPageInfo();
        mEmptyLayout.setRetryListener(() -> {
            mMessageAdapter.cleanItems();
            mPresenter.loadPageInfo();
        });
        MessageCenter.getInstance().register(this);
        mUserId = UserUtils.getUserId();
    }


    @Override
    public void cancel() {
        SwipeRefreshHelper.controlRefresh(mSwipeRefresh, false);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mPresenter.detachView();
        mToast.cancel();
        EventBus.getDefault().unregister(this);
        MessageCenter.getInstance().unregister(this);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleBindEvent(BindEvent event) {
        if (event.code == BindEvent.SUCCESS) {
            String userId = UserUtils.getUserId();
            if (mUserId.equals(userId)) {
                return;
            }
            mUserId = userId;
            mMessageBeen.clear();
            mMessageAdapter.notifyDataSetChanged();
            mPresenter.calcTotalPage();
            mPresenter.loadPageInfo();
        }
    }

    @Override
    public void loadComplete() {
        cancel();
        mToast.show();
    }

    @Override
    public void showContent(List<MessageBean> list) {
        int size = mMessageBeen.size();
        mMessageBeen.addAll(0, list);
        SwipeRefreshHelper.controlRefresh(mSwipeRefresh, false);
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
        if (size <= 0) {
            mRecylerView.scrollToPosition(mMessageBeen.size() - 1);
        }
        mMessageAdapter.notifyDataSetChanged();
    }

    @Override
    public void showError(int errCode, String errDesc) {
        if (Utils.isEmptyList(mMessageBeen)) {
            mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_DATA);
            SwipeRefreshHelper.controlRefresh(mSwipeRefresh, false);
        }
    }

    @Override
    public void showLoading(String s) {
        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_LOADING);
    }

    @Override
    public void dismissLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    @Override
    public void diposeMessage(MessageBean bean) {
        if (bean != null) {
            mMessageBeen.add(bean);
            mRecylerView.scrollToPosition(mMessageBeen.size() - 1);
            mMessageAdapter.notifyDataSetChanged();
            if (mEmptyLayout != null) {
                mEmptyLayout.hide();
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
    }


}
